package cn.wolfcode.util;

import cn.wolfcode.domain.SystemLog;
import com.alibaba.druid.support.json.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

public class LogManagerSetUtil {

    public static SystemLog getLogManager(Long handlerTime, RequiredPermission annotation, Boolean success, RuntimeException e) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Map parameterMap = ParameterMapUtil.getParameterMap(request);
        SystemLog logManager = new SystemLog();

        logManager.setPrameter(JSONUtils.toJSONString(parameterMap));
        logManager.setOperationPs(annotation.name());
        logManager.setOperationMethod(annotation.expression());
        logManager.setIp(IPUtil.getIpAddr(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()));
        logManager.setOperationTime(new Date());
        logManager.setUsername(UserContext.getCurrentUser().getUsername());
        //执行一个方法所花费的时间
        logManager.setHandlerTime(handlerTime);
        if (success) {//正常执行
            logManager.setResultMsg("无");
            logManager.setHandlerResult(true);
        } else {//出错
            logManager.setResultMsg(e.getMessage());
            logManager.setHandlerResult(false);
        }
        return logManager;
    }
}
